//自定义js

//公共配置
$(document).ready(function () {
	$("body").removeClass("skin-2");
    $("body").removeClass("skin-3");
    $("body").addClass("skin-1");
	var flag=false;
	var reg=/^(?=.*?[a-zA-Z])(?=.*?[0-6])[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~A-Za-z0-9]{10,16}$/;
	$('#newpassword').blur(function(){
		var val = $(this).val();
		var password = $('#oldpassword').val();
		if(val==null || val==""){
			$('#nptips').html("请输入密码");
			$('#nptips').css({"margin-top":"-15px","margin-bottom":"-3px"});
			flag=false;
		}else if(!reg.test(val)){
			$('#nptips').html("密码格式不正确");
			$('#nptips').css({"margin-top":"-15px","margin-bottom":"-3px"});
			flag=false;
		}else if(val==password){
			$('#nptips').html("新密码与原密码一致");
			$('#nptips').css({"margin-top":"-15px","margin-bottom":"-3px"});
			flag=false;
		}else{
			$('#nptips').css({"margin-top":"0px","margin-bottom":"0px"});
			$('#nptips').html("");
			flag=true;
		}
	});
	$('#checkpassword').blur(function(){
		var password = $('#newpassword').val();
		var val = $(this).val();
		if(val==null || val==""){
			$('#cptips').html("请再次输入密码");
			$('#cptips').css({"margin-top":"-15px","margin-bottom":"3px"});
			flag=false;
		}else if(password!=val){
			$('#cptips').html("两次密码不一致");
			$('#cptips').css({"margin-top":"-15px","margin-bottom":"3px"});
			flag=false;
		}else{
			$('#cptips').css({"margin-top":"0px","margin-bottom":"3px"});
			$('#cptips').html("");
			flag=true;
		}
	});
	doModiPassword = function(id,username) {
		var params = {
			'id' : id,
			'username' : username,
			'password' : $("#newpassword").val(),
			'prarm ': '应该是做了啥事'
		};
		/*$('#oldpassword').blur();*/
		getPassword(id,username);
		if(flag){
			$('#newpassword').blur();
			if(flag){
				$('#checkpassword').blur();
				if(flag){
					//异步请求
					$.ajax({
						url : '/admin/updatePassword',
						type : 'post',
						data : params,
						dataType : 'json',
						success : function(data) {
							if (data.status == 200) {
								
								$("#modal-form").modal('hide');
								layer.msg('修改成功,下次登陆生效', {icon: 1});
							}else if(data=="201"){
								layer.msg('未授权', {icon: 5});
							} else if (data.status == 0) {
								layer.msg('修改失败', {icon: 2});
							}
						},
						error : function() {
							layer.msg('未知错误', {icon: 2});
						}
					});
				}
			}
		}else{
			return false;
		}
		

	}
	
	
	getPassword = function(id,username) {
		var params = {
			'id' : id,
			'username' : username,
			'password' : $("#oldpassword").val(),
			'prarm ': '应该是做了啥事'
		};
		var val = $("#oldpassword").val();
		if(val==null || val==""){
			$('#optips').html("请输入原密码");
			$('#optips').css({"margin-top":"-15px","margin-bottom":"-3px"});
			flag=false;
		}else{
			//异步请求
			$.ajax({
				url : '/admin/getPassword',
				type : 'post',
				data : params,
				dataType : 'json',
				success : function(data) {
					if (data.status == 200) {
						$('#optips').css({"margin-top":"0px","margin-bottom":"0px"});
						$('#optips').html("");
						flag=true;
					} else if (data.status == 0) {
						$('#optips').css({"margin-top":"-15px","margin-bottom":"-3px"});
						$('#optips').html("原密码错误");
						flag=false;
					}
				},
				error : function() {
					layer.msg('未知错误', {icon: 2});
				}
			});
			
		}
		
		
		

	}
	
	
	
	
	
	
	
	
	
	
	//MetsiMenu
    $('#side-menu').metisMenu();

    // 打开右侧边栏
    $('.right-sidebar-toggle').click(function () {
        $('#right-sidebar').toggleClass('sidebar-open');
    });

    // 右侧边栏使用slimscroll
    $('.sidebar-container').slimScroll({
        height: '100%',
        railOpacity: 0.4,
        wheelStep: 10
    });

    // 打开聊天窗口
    $('.open-small-chat').click(function () {
        $(this).children().toggleClass('fa-comments').toggleClass('fa-remove');
        $('.small-chat-box').toggleClass('active');
    });

    // 聊天窗口使用slimscroll
    $('.small-chat-box .content').slimScroll({
        height: '234px',
        railOpacity: 0.4
    });

    // Small todo handler
    $('.check-link').click(function () {
        var button = $(this).find('i');
        var label = $(this).next('span');
        button.toggleClass('fa-check-square').toggleClass('fa-square-o');
        label.toggleClass('todo-completed');
        return false;
    });

    //固定菜单栏
    $(function () {
        $('.sidebar-collapse').slimScroll({
            height: '100%',
            railOpacity: 0.9,
            alwaysVisible: false
        });
    });


    // 菜单切换
    $('.navbar-minimalize').click(function () {
        $("body").toggleClass("mini-navbar");
        SmoothlyMenu();
    });


    // 侧边栏高度
    function fix_height() {
        var heightWithoutNavbar = $("body > #wrapper").height() - 61;
        $(".sidebard-panel").css("min-height", heightWithoutNavbar + "px");
    }
    fix_height();

    $(window).bind("load resize click scroll", function () {
        if (!$("body").hasClass('body-small')) {
            fix_height();
        }
    });

    //侧边栏滚动
    $(window).scroll(function () {
        if ($(window).scrollTop() > 0 && !$('body').hasClass('fixed-nav')) {
            $('#right-sidebar').addClass('sidebar-top');
        } else {
            $('#right-sidebar').removeClass('sidebar-top');
        }
    });

    $('.full-height-scroll').slimScroll({
        height: '100%'
    });

    $('#side-menu>li').click(function () {
        if ($('body').hasClass('mini-navbar')) {
            NavToggle();
        }
    });
    $('#side-menu>li li a').click(function () {
        if ($(window).width() < 769) {
            NavToggle();
        }
    });

    $('.nav-close').click(NavToggle);

    //ios浏览器兼容性处理
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        $('#content-main').css('overflow-y', 'auto');
    }

});

$(window).bind("load resize", function () {
    if ($(this).width() < 769) {
        $('body').addClass('mini-navbar');
        $('.navbar-static-side').fadeIn();
    }
});

function NavToggle() {
    $('.navbar-minimalize').trigger('click');
}

function SmoothlyMenu() {
    if (!$('body').hasClass('mini-navbar')) {
        $('#side-menu').hide();
        setTimeout(
            function () {
                $('#side-menu').fadeIn(500);
            }, 100);
    } else if ($('body').hasClass('fixed-sidebar')) {
        $('#side-menu').hide();
        setTimeout(
            function () {
                $('#side-menu').fadeIn(500);
            }, 300);
    } else {
        $('#side-menu').removeAttr('style');
    }
}

//主题设置
$(function () {

    // 顶部菜单固定
    $('#fixednavbar').click(function () {
        if ($('#fixednavbar').is(':checked')) {
            $(".navbar-static-top").removeClass('navbar-static-top').addClass('navbar-fixed-top');
            $("body").removeClass('boxed-layout');
            $("body").addClass('fixed-nav');
            $('#boxedlayout').prop('checked', false);

            if (localStorageSupport) {
                localStorage.setItem("boxedlayout", 'off');
            }

            if (localStorageSupport) {
                localStorage.setItem("fixednavbar", 'on');
            }
        } else {
            $(".navbar-fixed-top").removeClass('navbar-fixed-top').addClass('navbar-static-top');
            $("body").removeClass('fixed-nav');

            if (localStorageSupport) {
                localStorage.setItem("fixednavbar", 'off');
            }
        }
    });


    // 收起左侧菜单
    $('#collapsemenu').click(function () {
        if ($('#collapsemenu').is(':checked')) {
            $("body").addClass('mini-navbar');
            SmoothlyMenu();

            if (localStorageSupport) {
                localStorage.setItem("collapse_menu", 'on');
            }

        } else {
            $("body").removeClass('mini-navbar');
            SmoothlyMenu();

            if (localStorageSupport) {
                localStorage.setItem("collapse_menu", 'off');
            }
        }
    });

    // 固定宽度
    $('#boxedlayout').click(function () {
        if ($('#boxedlayout').is(':checked')) {
            $("body").addClass('boxed-layout');
            $('#fixednavbar').prop('checked', false);
            $(".navbar-fixed-top").removeClass('navbar-fixed-top').addClass('navbar-static-top');
            $("body").removeClass('fixed-nav');
            if (localStorageSupport) {
                localStorage.setItem("fixednavbar", 'off');
            }


            if (localStorageSupport) {
                localStorage.setItem("boxedlayout", 'on');
            }
        } else {
            $("body").removeClass('boxed-layout');

            if (localStorageSupport) {
                localStorage.setItem("boxedlayout", 'off');
            }
        }
    });

    // 默认主题
    $('.s-skin-0').click(function () {
        $("body").removeClass("skin-1");
        $("body").removeClass("skin-2");
        $("body").removeClass("skin-3");
        return false;
    });

    // 蓝色主题
    $('.s-skin-1').click(function () {
        $("body").removeClass("skin-2");
        $("body").removeClass("skin-3");
        $("body").addClass("skin-1");
        return false;
    });

    // 黄色主题
    $('.s-skin-3').click(function () {
        $("body").removeClass("skin-1");
        $("body").removeClass("skin-2");
        $("body").addClass("skin-3");
        return false;
    });

    if (localStorageSupport) {
        var collapse = localStorage.getItem("collapse_menu");
        var fixednavbar = localStorage.getItem("fixednavbar");
        var boxedlayout = localStorage.getItem("boxedlayout");

        if (collapse == 'on') {
            $('#collapsemenu').prop('checked', 'checked')
        }
        if (fixednavbar == 'on') {
            $('#fixednavbar').prop('checked', 'checked')
        }
        if (boxedlayout == 'on') {
            $('#boxedlayout').prop('checked', 'checked')
        }
    }

    if (localStorageSupport) {

        var collapse = localStorage.getItem("collapse_menu");
        var fixednavbar = localStorage.getItem("fixednavbar");
        var boxedlayout = localStorage.getItem("boxedlayout");

        var body = $('body');

        if (collapse == 'on') {
            if (!body.hasClass('body-small')) {
                body.addClass('mini-navbar');
            }
        }

        if (fixednavbar == 'on') {
            $(".navbar-static-top").removeClass('navbar-static-top').addClass('navbar-fixed-top');
            body.addClass('fixed-nav');
        }

        if (boxedlayout == 'on') {
            body.addClass('boxed-layout');
        }
    }
});
//修改用户信息
function updateBloger(id) {
	var imagePath=null;
	if($("#imagePath").val()!="" && $("#imagePath").val()!=null){
		imagePath=$("#imagePath").val();
	}
	var prarm = "";
	var params = {
		'id' : id,
		'name' : $("#name").val(),
		'email' : $("#email").val(),
		'sex' : $('input[type=radio][name=sex]:checked').val(),
		'roleId' : $('input[type=radio][name=roleId]:checked').val(),
		'headImageUrl' : imagePath,
		'status' : $('input[type=radio][name=status]:checked').val(),
		prarm : prarm
	};
	$.ajax({
		url : '/admin/updateBlogerByPerson',
		type : 'post',
		data : params,
		dataType : 'json',
		success : function(data) {
			if (data.status == 200) {
				$("#headImage").attr("href",$("#imagePath").val());
				$("#headImgUrl").attr("src",$("#imagePath").val());
				$("#myModal").modal('hide');
				$('#allBlog').bootstrapTable('refresh');
				layer.msg('更新成功', {icon: 1});
			}else if(data=="201"){
				layer.msg('未授权', {icon: 5});
			} else {
				layer.msg('更新失败', {icon: 2});
			}
		},
		error : function() {
			layer.msg('更新错误', {icon: 2});
		}
	});

}
//查看用户信息
function selectBlogById(blogerId) {
	var param = {
		id : blogerId
	}
	$.ajax({
		url : '/admin/selectBlogerById',//这个地址在服务器要改成：/admin/selectBlogerById
		type : 'post',
		data : param,
		dataType : 'json',
		success : function(data) {
			//查询成功
			if (data.status == 200) {
				console.log(data,"通过ID查找的用户");
				$(".newsview").find("#name").val(data.blogerRole.bloger.name);
				$(".newsview").find("#username").val(data.blogerRole.bloger.username);
				$(".newsview").find("#email").val(data.blogerRole.bloger.email);
				
				//$(".newsview").find(".au02").html(Format(data.blog.addtime, "yyyy-MM-dd hh:mm:ss"));
				var man = '<label class="radio-inline"> <input type="radio" name="sex" value="1" checked="checked" /> 男 </label><label class="radio-inline"> <input type="radio" name="sex" value="0" /> 女 </label> ';
				var woman = '<label class="radio-inline"> <input type="radio" name="sex" value="1" /> 男 </label><label class="radio-inline"> <input type="radio" name="sex" checked="checked" value="0" /> 女 </label> ';
				var normal='<label class="radio-inline"> <input type="radio" disabled="disabled" name="status" checked="checked" value="1" /> 正常 </label><label class="radio-inline"> <input type="radio" disabled="disabled" name="status" value="2" /> 禁用 </label> ';
				var unallow='<label class="radio-inline"> <input type="radio" disabled="disabled" name="status" value="1" /> 正常 </label><label class="radio-inline"> <input type="radio" disabled="disabled" name="status" checked="checked" value="2" /> 禁用 </label> ';
				var supperAdmin='<label class="radio-inline"> <input type="radio" disabled="disabled" name="roleId" checked="checked" value="1" /> 超级管理员 </label><label class="radio-inline"> <input type="radio" disabled="disabled" name="roleId" value="2" /> 普通用户 </label> ';
				var user='<label class="radio-inline"> <input type="radio" disabled="disabled" name="roleId" value="1" /> 超级管理员 </label><label class="radio-inline"> <input type="radio" disabled="disabled" name="roleId" checked="checked" value="2" /> 普通用户 </label> ';
				if(data.blogerRole.bloger.sex==1){
					$("#sex").html(man);
				}else{
					$("#sex").html(woman);
				}
				if(data.blogerRole.bloger.status==1){
					$("#status").html(normal);
				}else{
					$("#status").html(unallow);
				}
				if(data.blogerRole.role.id==1){
					$("#roleId").html(supperAdmin);
				}else{
					$("#roleId").html(user);
				}
				//$('input[type=radio][name=status][value="'+data.blogerRole.bloger.status+'"]').attr("checked",'checked');
				//$('input[type=radio][name=sex][value="'+data.blogerRole.bloger.sex+'"]').attr("checked",'checked');
				//$('input[type=radio][name=roleId][value="'+data.blogerRole.role.id+'"]').attr("checked",'checked');
				var update = '<button  class="J_menuItem btn btn-white" onclick="updateBloger(' + data.blogerRole.blogerId + ')">保存</button>';
				$(".modal-footer").find(".update").html(update);
				
			}else if(data=="201"){
				layer.msg('未授权', {icon: 5});
			}
			$('pre').each(function(i, block) {
				hljs.highlightBlock(block);
			});
		},
		error : function() {
			layer.msg('未知错误', {icon: 2});
		}
	});
}

//图片上传  
function sendFile(file, editor, $editable) {
	var filename = false;
	try {
		filename = file['name'];
	} catch (e) {
		filename = false;
	}
	if (!filename) {
		$(".note-alarm").remove();
	}
	//以上防止在图片在编辑器内拖拽引发第二次上传导致的提示错误  
	data = new FormData();
	data.append("file", file);
	data.append("key", filename); //唯一性参数  
	$.ajax({
		data : data,
		type : "POST",
		url : "/admin/uploadBg",
		dataType : "json",
		cache : false,
		contentType : false,
		processData : false,
		success : function(data) {
			if (data.status == 200) {
				layer.msg('上传成功', {icon: 1});
			}else if(data.status == "201"){
				layer.msg('未授权', {icon: 5});
			} else {
				layer.msg('上传失败', {icon: 2});
			}
			editor.insertImage($editable, data.path);
		},
		error : function() {
			layer.msg('未知错误', {icon: 2});
		}
	});
}


//弹出模态框 选择图片
var selectImgPath = function(img) {
	$("#pic").modal('hide');
	$("#imagePath").val(img.src);
	$("#headImage").attr("href",img.src);
	//$("#headImgUrl").attr("src",img.src);
	$("#changeImg").attr("src",img.src);
};

//查找服务器图库
var findPicList = function() {
	$.ajax({
		//此处使用的是自己封装的JAVA类
		url : "/admin/getFileList",
		type : "POST",
		success : function(data) {
			if (data.status == 0) {
				layer.msg('服务器图库为空', {icon: 5});
			}else if(data == 201){
				layer.msg('获取服务器图片列表未授权', {icon: 5});
			} else {
				var pics = '';
				for (var i = 0; i < data.fileList.length; i++) {
					pics += '<a class="fancybox" href="javascript:void(0);"><img onclick="selectImgPath(this)" style="width: 190px; height: 115px;float:left;margin-right:3px;" alt="image" src="' + data.fileList[i] + '" /></a>'
				}
			}
			$(".picsList").html(pics);
		},
		error : function(e) {
			layer.msg('未知错误', {icon: 2});
		}
	});
};


//判断浏览器是否支持html5本地存储
function localStorageSupport() {
    return (('localStorage' in window) && window['localStorage'] !== null)
}
